import time
import usocket 
from esp32 import Partition
import machine
import requests
import uzlib



def ota_pac():
    SEC_SIZE = 4096
    buf = bytearray(SEC_SIZE)
    write_buf = bytearray(SEC_SIZE)
    i = 0
    currentPartition = Partition(Partition.RUNNING)
    nextPartition = currentPartition.get_next_update()
    assert nextPartition.ioctl(5,0) == SEC_SIZE
    SEC_COUNT = nextPartition.ioctl(4,0)

    host = 'test240509.oss-cn-shanghai.aliyuncs.com'
    path = 'micropython.bin'

    s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    addr = usocket.getaddrinfo(host, 80)[0][-1]
    print('addr:', addr)
    s.connect(addr)
    print('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host))
    s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
    while True:
        if i > SEC_COUNT:
            print("attempt to write more sectors than available")
        buf = s.read(SEC_SIZE)
        if buf:
            if i == 0: #第一包数据包含文件数据和服务器响应数据
                headers, body = buf.split(b"\r\n\r\n", 1)
                write_buf = body

            if i > 0:
                if len(buf) < len(headers) + len('\r\n\r\n'):
                    buf = buf + bytes(b'\xff'*(len(headers) + len('\r\n\r\n') - len(buf)))
                    write_buf += buf
                    nextPartition.writeblocks(i - 1, write_buf)
                    break

                if len(buf) < SEC_SIZE and len(buf) > len(headers) + len('\r\n\r\n'):
                    print('adding padding to sector')
                    write_buf += buf[:len(headers) + len('\r\n\r\n')]
                    nextPartition.writeblocks(i - 1, write_buf)
                    buf = buf[len(headers) + len('\r\n\r\n'):] + bytes(b'\xff'*(4096 + len(headers) + len('\r\n\r\n') - len(buf)))
                    nextPartition.writeblocks(i, buf)
                    break

                write_buf += buf[:len(headers) + len('\r\n\r\n')]
                nextPartition.writeblocks(i - 1, write_buf)
                write_buf = buf[len(headers) + len('\r\n\r\n'):]

            i += 1
        else:
            break
    s.close()
    print('done')
    nextPartition.set_boot()
    time.sleep(1)
    machine.reset()
    


def unzlib_files(input_file):
    with open(input_file, 'rb') as f:
        data = f.read()
    files = data.split(b'\x1a\x1b\x1c\x1d\x1e')
    for file in files:
        if file:
            for byte in file:
                print(hex(byte), end=" ")
            file_name, compressed_data = file.split(b'\x5a\x5b\x5c\x5d\x5e')
            file_data = uzlib.decompress(compressed_data)
            with open(file_name.decode(), 'wb') as f:
                f.write(file_data)

def ota_py(url):
    response = requests.get(url)
    # 检查响应状态码
    if response.status_code == 200:
        # 获取响应内容
        content = response.content
        print(content)
        with open('out.zlib', 'wb') as f:
            f.write(content)
            print('下载成功！')
            f.close()
            unzlib_files('out.zlib')
            print('解压成功')
            time.sleep(1)
            machine.reset()
    else :
        print("Error:", response.status_code)
    # 关闭响应对象
    response.close()
